from django.conf import settings
import redis

__author__ = 'lee'

host = settings.REDIS.get("host")
port = settings.REDIS.get("port")
password = settings.REDIS.get("password")

pool = redis.ConnectionPool(host=host, port=port, password=password, db=0, decode_responses=True)


def check(conn, key, value):
    """
    对比value与服务器上的value是否一致

    :param conn:
    :param key:
    :param value:
    :return: boolean
    """
    try:
        redis_value = str(conn.get(key), "utf-8")
        return True if redis_value == value else False
    except TypeError:
        return False


class RedisQueue(object):
    def __init__(self, connect, key):
        self._conn = connect
        self._key = key

    def size(self):
        return self._conn.llen(self._key)

    def put(self, item):
        self._conn.rpush(self._key, item)

    def get_wait(self, timeout=None):
        item = self._conn.blpop(self._key, timeout=timeout)
        return item

    def get_nowait(self):
        item = self._conn.lpop(self._key)
        return item

    def reset(self):
        self._conn.delete(self._key)
